// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

package com.faceunity.nama.seekbar.internal.drawable;

import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Animatable;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import com.faceunity.nama.seekbar.internal.Marker;

/**
 *
 *
 * <h1>HACK</h1>
 *
 * <p>Special {@link StateDrawable} implementation to draw the Thumb circle.
 *
 * <p>It's special because it will stop drawing once the state is pressed/focused BUT only after a
 * small delay.
 *
 * <p>This special delay is meant to help avoiding frame glitches while the {@link Marker} is added
 * to the Window
 *
 * @hide
 */
public class ThumbDrawable extends StateDrawable implements Animatable {
  //The current size for this drawable. Must be converted to real DPs
  public static final int DEFAULT_SIZE_DP = 12;
  private final int mSize;
  private boolean mOpen;
  private boolean mRunning;

  public ThumbDrawable(@NonNull ColorStateList tintStateList, int size) {
    super(tintStateList);
    mSize = size;
  }

  @Override
  public int getIntrinsicWidth() {
    return mSize;
  }

  @Override
  public int getIntrinsicHeight() {
    return mSize;
  }

  @Override
  public void doDraw(Canvas canvas, Paint paint) {
    if (!mOpen) {
      Rect bounds = getBounds();
      float radius = (mSize / 2);
      canvas.drawCircle(bounds.centerX(), bounds.centerY(), radius, paint);
    }
  }

  public void animateToPressed() {
    scheduleSelf(opener, SystemClock.uptimeMillis() + 100);
    mRunning = true;
  }

  public void animateToNormal() {
    mOpen = false;
    mRunning = false;
    unscheduleSelf(opener);
    invalidateSelf();
  }

  private Runnable opener =
      new Runnable() {
        @Override
        public void run() {
          mOpen = true;
          invalidateSelf();
          mRunning = false;
        }
      };

  @Override
  public void start() {
    //NOOP
  }

  @Override
  public void stop() {
    animateToNormal();
  }

  @Override
  public boolean isRunning() {
    return mRunning;
  }
}
